package com.yaoq.proxy.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName JDKProxy
 * @Description TODO
 * @Author yaoqiang
 * @Date 2020/9/2 10:00
 * @Version 1.0
 */
public class JDKProxy implements InvocationHandler {
    private Object target;
    private String interceptClass = null;

    public JDKProxy(Object target, String interceptClass) {
        this.target = target;
        this.interceptClass = interceptClass;
    }

    public static Object getProxy(Object target, String interceptClass) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new JDKProxy(target, interceptClass));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //没有拦截器，直接反射原有的方法
        if (interceptClass == null) {
            return method.invoke(target, args);
        }

        Object result = null;
        //反射取得拦截器
        Interceptor interceptor = (Interceptor) Class.forName(interceptClass).newInstance();
        //调用前置方法
        if (interceptor.before(proxy, target, method, args)) {
            result = method.invoke(target, args);
        } else {
            //调用前置方法
            interceptor.after(proxy, target, method, args);
        }
        //
        interceptor.after(proxy, target, method, args);

        return result;
    }
}














